package com.crape.common.thread;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crape.common.bean.LoginUser;

/**
 * @author ChenKai
 */
@SuppressWarnings("unchecked")
public class ThreadObjManager {

    private static final String           THREADKEY_LOGINUSER = "threadkey_loginuser";

    private static final ThreadLocal<Map> threadObjPool       = new ThreadLocal<Map>();

    private static final Log              log                 = LogFactory.getLog("login");

    /**
     * set the LoginUser threadObjPool
     * 
     * @param userObj
     */
    public static void setLoginUser(LoginUser userObj) {
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap != null) {
            servletAttributesMap.clear();
        }
        servletAttributesMap = new HashMap();
        threadObjPool.set(servletAttributesMap);
        servletAttributesMap.put(THREADKEY_LOGINUSER, userObj);
    }

    /**
     * get the LoginUser from threadObjPool
     * 
     * @return
     */
    public static LoginUser getLoginUser() {
        LoginUser loginUser = null;
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap != null) {
            loginUser = (LoginUser) servletAttributesMap.get(THREADKEY_LOGINUSER);
        }
        if (loginUser == null) {
        	return new LoginUser();
        }
        return loginUser;
    }

    /**
     * clear the threadObjPool map
     */
    public static void clear() {
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap != null) {
            servletAttributesMap.clear();
        }
    }
}
